﻿using MediatR;
using Warehouse.API.Applcation.Command.WarehouseCommand;
using Warehouse.Domain;
using Warehouse.Infrstructre.Interface;

namespace Warehouse.API.Applcation.CommandHandlers.WarehouseCommandHndlers
{
    public class CreateWarehouseCommandHandlers : IRequestHandler<CreateWarehouseCommand, int>
    {
        private readonly IWarehouseRepository _warehouse;

        public CreateWarehouseCommandHandlers(IWarehouseRepository warehouse)
        {
            _warehouse = warehouse;
        }

        public async Task<int> Handle(CreateWarehouseCommand request, CancellationToken cancellationToken)
        {
            // 获取所有仓库记录一次
            var warehouses = await _warehouse.GetAllAsyns();

            // 检查是否已存在相同的 WarehouseName 和 WarehouseType
            if (warehouses.Any(x => x.WarehouseName == request.WarehouseName && x.WarehouseType == request.WarehouseType))
            {
                return -1;  // 如果找到了符合条件的仓库，返回 -1
            }

            // 检查是否已存在相同的 WarehouseCode
            if (warehouses.Any(x => x.WarehouseCode == request.WarehouseCode))
            {
                return -2;  // 如果找到了符合条件的仓库，返回 -2
            }


            return await _warehouse.AddAsync(new Warehouseinfo() { WarehouseId = request.WarehouseId, WarehouseCode = request.WarehouseCode, WarehouseName = request.WarehouseName, RentalTime = request.RentalTime, WarehouseType = request.WarehouseType, Department = request.Department, IsDefaults = request.IsDefaults, IsDisable = request.IsDisable, Waddress = request.Waddress, Area = request.Area, Wcontact = request.Wcontact, Wphone = request.Wphone, Function = request.Function, AddName = request.AddName, AddTime = request.AddTime, office_id = request.office_id, user_id = request.user_id });

        }
    }
}
